import { EStorage } from "./storage.enum";

export interface IStorageOptions {
  /** 唯一key */
  rootKey: string;
  /** 存储的类型 */
  type?: "local" | "session";
}

/**
 * 存储服务
 */
export class StorageService<T = string> {
  private rootKey: string;
  private storage: Storage;

  constructor(options: IStorageOptions) {
    const { rootKey, type = "local" } = options;
    this.rootKey = rootKey;
    this.storage = {
      local: localStorage,
      session: sessionStorage,
    }[type];
  }

  /**
   * 获取缓存
   * @param key
   */
  get(key?: T): any {
    const json = JSON.parse(this.storage.getItem(this.rootKey) || "{}");
    return key ? json[key] : json;
  }

  /**
   * 设置缓存
   * @param key
   * @param value
   */
  set(key: T, value: any): StorageService<T> {
    const json = this.get();
    if (typeof key === "string") {
      this.storage.setItem(
        this.rootKey,
        JSON.stringify({
          ...json,
          [key]: value,
        })
      );
    }
    return this;
  }

  /**
   * 删除单个缓存
   * @param key
   */
  remove(key: T) {
    const json = this.get();
    delete json[key];
    this.storage.setItem(this.rootKey, JSON.stringify(json));
  }

  /**
   * 清空缓存
   */
  clear() {
    this.storage.removeItem(this.rootKey);
  }
}

export const storage = new StorageService<EStorage>({ rootKey: "ONEBUY_B2C" });
